<template>
  <div class="login">
    <div v-if="!tag" class="main">
      <div>
        <h2>云管理</h2>

        <label v-if="!phonein"
          >账 号:
          <el-input
            class="input_info"
            v-model="input_account"
            placeholder="请输入您的账号"
            clearable
        /></label>

        <label v-if="!phonein"
          >密 码:
          <el-input
            class="input_info"
            v-model="input_password"
            type="password"
            placeholder="请输入您的密码"
            show-password
        /></label>

        <label v-if="phonein"
          >手机号:
          <el-input
            class="input_info"
            v-model="input_phone"
            placeholder="请输入您的手机号"
            clearable
        /></label>

        <label  v-if="phonein">
          <div class="inner_judge">
            验证码:
            <el-input class="input_judge" v-model="input_judge" clearable />
            <el-button
              v-if="!yanzhengma"
              class="btn_judge"
              type="primary"
              @click="SendMSS"
              round
              >获取验证码</el-button
            >
            <el-button
              v-if="yanzhengma"
              class="btn_judge"
              type="primary"
              round
              >{{ timeend + "S" }}</el-button
            >
          </div>
        </label>



        <div v-if="!phonein" @click="phonein = true" class="phonein">
          切换至手机号登录
        </div>
        <div v-if="phonein" @click="phonein = false" class="phonein">
          切换至用户名登录
        </div>

        <el-row class="mb-4 outerbtn">
          <el-button class="btn btn1" type="primary" @click="tag = !tag" round
            >注册</el-button
          >
          <el-button class="btn" type="success" @click="Login" round
            >登录</el-button
          >
        </el-row>
        <!-- 应该可以切换至手机登录 -->
      </div>
    </div>
    <div v-if="tag" class="main change">
      <div>
        <h2>云管理</h2>
        <!-- 手机号 验证码  -->
        <label
          >账 号:
          <el-input
            class="input_info"
            v-model="input_account"
            placeholder="请输入您的账号"
            clearable
        /></label>

        <label
          >姓 名:
          <el-input
            class="input_info"
            v-model="input_name"
            placeholder="请输入您的账号"
            clearable
        /></label>

        <label
          >密 码:
          <el-input
            class="input_info"
            v-model="input_password"
            type="password"
            placeholder="请输入您的密码"
            show-password
        /></label>

        <label
          >手 机:
          <el-input
            class="input_info"
            v-model="input_phone"
            placeholder="请输入您的账号"
            clearable
        /></label>

        <div class="sex">
          性 别:
          <el-radio-group v-model="radio">
            <el-radio :label="3">男</el-radio>
            <el-radio :label="6">女</el-radio>
          </el-radio-group>
        </div>

        <div class="demo-date-picker">
          出生日期:
          <el-date-picker v-model="date" type="date" placeholder="Pick a day">
          </el-date-picker>
        </div>

        <label>
          <div class="inner_judge">
            验证码:
            <el-input class="input_judge" v-model="input_judge" clearable />
            <el-button
              v-if="!yanzhengma"
              class="btn_judge"
              type="primary"
              @click="SendMSS"
              round
              >获取验证码</el-button
            >
            <el-button
              v-if="yanzhengma"
              class="btn_judge"
              type="primary"
              round
              >{{ timeend + "S" }}</el-button
            >
          </div>
        </label>

        <el-button class="btn" @click="zhuce" type="success" round
          >注册</el-button
        >

        <span class="back" @click="tag = !tag">返回</span>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import axios from "axios";
import { useStore } from "vuex";
import { nanoid } from "nanoid";
import router from '../router/index.js'
export default {
  name: "Login",
  setup() {
    // tag === false 登录 tag === true 注册
    let tag = ref(false);
    // 用户名
    const input_account = ref("");
    // 密码
    const input_password = ref("");
    // 姓名
    const input_name = ref("");
    // 日期
    const date = ref("");
    // 性别
    const radio = ref(2);
    // 手机号
    const input_phone = ref("");
    // 验证码
    const input_judge = ref("");
    // 验证码框提示信息
    const yanzhengma = ref(false);
    // 倒计时
    const timeend = ref(60);
    // 手机号登陆
    let phonein = ref(false);
    const store = useStore();

    function Login() {
      // 登录
      if(phonein.value == false){
        axios({
        method: "post",
        url: "https://qcjk2s.api.cloudendpoint.cn/hello",
        data: {
          name: input_account.value.trim(),
          password: input_password.value,
        },
      }).then(
        (res) => {
          let data = res.data;
          if (data === -1) return alert("用户名或密码错误");
          // localStorage.setItem("person", JSON.stringify(data.user[0]));
          let date = {
            year: new Date().getYear(),
            month: new Date().getMonth(),
            day: new Date().getDate(),
            hour: new Date().getHours(),
          };
          // localStorage.setItem("lasttime", JSON.stringify(date));
          store.commit('UpdateState',[data.user[0],data.item,data.demand,data.user[0].lastItemID])
          // 进行sessionStorage存储 名称叫做cloud
          sessionStorage.setItem("cloud", JSON.stringify(store.state));
          // console.log(JSON.parse(sessionStorage.getItem('cloud')))
          router.push('/main/organizationInfo')
        },
        (err) => {
          console.log(err.message);
        }
      );
      }else{
        axios({
        method: "post",
        url: "https://qcjk2s.api.cloudendpoint.cn/loginbyphone",
        data: {
          phone:input_phone.value.trim()
        },
      }).then(
        (res) => {
          let data = res.data;
          if (data === -1) return alert("该用户不存在");
          // localStorage.setItem("person", JSON.stringify(data.user[0]));
          let date = {
            year: new Date().getYear(),
            month: new Date().getMonth(),
            day: new Date().getDate(),
            hour: new Date().getHours(),
          };
          // localStorage.setItem("lasttime", JSON.stringify(date));
          store.commit('UpdateState',[data.user[0],data.item,data.demand,data.user[0].lastItemID])
          sessionStorage.setItem("cloud", JSON.stringify(store.state));
          router.push('/main/organizationInfo')
        },
        (err) => {
          console.log(err.message);
        }
      );
      }
    }

    const InspireCloud = require("@byteinspire/js-sdk");
    const serviceId = "qcjk2s";
    const inspirecloud = new InspireCloud({ serviceId });

    function SendMSS() {
      // 发送验证码
      var reg_tel =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (input_phone.value.trim() == "") {
        return alert("手机号不能为空");
      } else if (!reg_tel.test(input_phone.value.trim())) {
        return alert("请正确填写您的手机号码！");
      }
      let x = input_phone.value.trim();
      return inspirecloud
        .run("sendMessageAPI", {
          x,
        })
        .then((res) => {
          yanzhengma.value = true;
          for (let i = 0; i < 60; i++) {
            setTimeout(() => {
              timeend.value--;
            }, 1000 * i);
            if (i == 59) {
              yanzhengma.value = false;
            }
          }
        });
    }

    function zhuce() {
      // 注册
      if (input_account.value.trim() == "") {
        return alert("用户名不能为空");
      }
      if (input_name.value.trim() == "") {
        return alert("姓名不能为空");
      }
      if (input_password.value.trim() == "") {
        return alert("密码不能为空");
      }
      var reg = /^\w{6,18}$/;
      if (!reg.test(input_password.value.trim())) {
        return alert("密码由6-18位的数字、字母、下划线组成");
      }

      if (date.value == "") {
        return alert("出生日期不能为空");
      }
      if (input_judge.value.trim() == "") {
        return alert("验证码不能为空");
      }

      let code = input_judge.value.trim();
      let phoneNumber = input_phone.value.trim();
      inspirecloud
        .run("loginAPI", {
          phoneNumber,
          code,
        })
        .then(() => {
          let sex = "";
          radio.value == 6 ? (sex = "女") : (sex = "男");
          let d = new Date();
          let age = 0;
          age = d.getYear() - date.value.getYear();
          if (d.getMonth() > date.value.getMonth()) {
            age++;
          }
          if (d.getMonth() == date.value.getMonth()) {
            if (d.getDate() >= date.value.getDate()) {
              age++;
            }
          }
          let realdate = `${date.value.getFullYear()}-${
            date.value.getMonth() - 0 + 1
          }-${date.value.getDate()}`;
          axios
            .get(
              `https://qcjk2s.api.cloudendpoint.cn/addUser?username=${input_account.value.trim()}&age=${age}&password=${input_password.value.trim()}&sex=${sex}&name=${input_name.value.trim()}&birthday=${realdate}&phone=${input_phone.value.trim()}&id=${nanoid()}`
            )
            .then(
              (res) => {
                if (res.data == -1) {
                  alert("注册失败,该用户名或手机号已存在");
                }
              },
              (err) => {
                console.log(err.message);
              }
            );
        });
    }

    onMounted(() => {
      // 如果localStorage中有用户信息则直接登录
      // let u = JSON.parse(localStorage.getItem("person"));
      // if (u !== null) {
      //   let date = new Date();
      //   let t = JSON.parse(localStorage.getItem("lasttime"));
      //   if (date.getHours() - t.hour >= 6) {
      //     localStorage.removeItem("person");
      //   } else if (date.getDate() - t.day >= 1) {
      //     localStorage.removeItem("person");
      //   } else if (date.getMonth() - t.month >= 1) {
      //     localStorage.removeItem("person");
      //   } else if (date.getYear() - t.year >= 1) {
      //     localStorage.removeItem("person");
      //   } else {
      //     axios({
      //       method: "post",
      //       url: "https://qcjk2s.api.cloudendpoint.cn/hello",
      //       data: {
      //         name: u.username,
      //         password: u.password,
      //       },
      //     }).then(
      //       (res) => {
      //         let data = res.data;
      //         if (data === -1) return alert("用户名或密码错误");
      //         store.state.usernow = data.user[0];
      //         store.state.ItemList = data.item;
      //         store.state.DemandList = data.demand;
      //         store.state.ItemID = data.user[0].lastItemID;
      //         store.state.ItemList.some((element) => {
      //           if (element.Item_ID === store.state.ItemID) {
      //             store.state.real_Item = element;
      //             store.state.main_person = element.main_person;
      //           }
      //         });
      //         store.state.DemandList.some((e) => {
      //           if (e.Item_ID == store.state.ItemID) {
      //             store.state.real_Demand.push(e);
      //           }
      //         });
      //         sessionStorage.setItem("cloud", JSON.stringify(store.state));
      //         window.location.hash = "#/main/organizationInfo";
      //       },
      //       (err) => {
      //         console.log(err.message);
      //       }
      //     );
      //     return;
      //   }
      // }
      // 这里应该检查localStorage中的属性有就获取信息存储vuex后直接跳转
      store.state.usernow = "";
      store.state.ItemList = "";
      store.state.DemandList = "";
      store.state.ItemID = "";
      store.state.real_Item = "";
      store.state.main_person = "";
      store.state.real_Demand = [];
    });

    return {
      tag,
      input_account,
      input_password,
      yanzhengma,
      timeend,
      date,
      input_name,
      radio,
      phonein,
      input_phone,
      input_judge,
      SendMSS,
      Login,
      zhuce,
    };
  },
};
</script>

<style lang="less" scoped>
.login {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .main {
    width: 30%;
    height: 50%;
    border: 1px solid #ccc;
    border-radius: 10px;
    box-shadow: 0px 0px 10px 5px #ccc;
    h2 {
      margin: 10% 0 10% 0;
    }
    label {
      display: block;
      margin-bottom: 5%;
      .input_info {
        width: 60%;
      }
      .inner_judge {
        margin-top: 5%;
        // margin-left: -36%;
        .input_judge {
          width: 20%;
        }
        .btn_judge {
          margin-left: 12%;
          width: 30%;
        }
      }
    }
    .phonein {
      margin: -3% 5% -3% 0;
      text-align: right;
      color: #409efc;
      cursor: pointer;
    }
    .outerbtn {
      margin-top: 7%;
    }
    .btn1 {
      margin-left: 15%;
    }
    .btn {
      width: 35%;
    }
    .back {
      font-size: 14px;
      display: block;
      float: right;
      cursor: pointer;
      margin: 5% 3% 0 0;
    }
  }
  .change {
    height: 80%;
    .sex {
      margin-left: -38%;
    }
  }
}

.demo-date-picker {
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  margin-left: -9%;
}
</style>